package com.zjdiepu.www.manage.api.dh;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.DataDicType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.enums.type.TypeData;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.UUIDFactory;
import com.zjdiepu.www.common.util.ZhppDateUtil;
import com.zjdiepu.www.config.FileProperty;
import com.zjdiepu.www.ibiz.cache.ICachedDictionaryService;
import com.zjdiepu.www.ibiz.dh.IDhOverdueLetterLawyersService;
import com.zjdiepu.www.ibiz.dh.IDhOverdueListService;
import com.zjdiepu.www.ibiz.dh.IDhOverdueTrailerService;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.dh.dto.DhOverdueLetterLawyers;
import com.zjdiepu.www.model.dh.dto.DhOverdueList;
import com.zjdiepu.www.model.dh.dto.DhOverdueTrailer;
import com.zjdiepu.www.model.dh.ext.DhOverdueTrailerExt;
import com.zjdiepu.www.model.dh.vo.DhOverdueTrailerVo;
import com.zjdiepu.www.model.yw.request.YwBusinessQueryRequest;

/**
 * Controller层<br/>
 * @author zhangzhengjian<br/>
 * @time 2017年06月08日 16时39分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "DhOverdueTrailerController", produces="application/json;charset=UTF-8")
@Api(tags = {""}, produces="application/json;charset=UTF-8")
public class DhOverdueTrailerController extends BaseController {
    @Resource
    private IDhOverdueTrailerService dhOverdueTrailerService;
    @Resource
    private ICachedDictionaryService cachedDictionaryService;
    @Resource
	private FileProperty fileProperty;
    @Resource
    private IDhOverdueListService dhOverdueListService;
    @Resource
    private IDhOverdueLetterLawyersService dhOverdueLetterLawyersService;

    /**
     * @author zhangzhengjian <br/>
     * @Title: save  <br/>
     * @Description: 新增 <br/>
     * @param dhOverdueTrailer
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute DhOverdueTrailer dhOverdueTrailer) {
    	AbstractSysUser currentUser = getCurrentUser();
    	Integer current = (int)(System.currentTimeMillis() / 1000);
    	String uuid=UUIDFactory.getUUID();
    	dhOverdueTrailer.setCreated(current);
    	dhOverdueTrailer.setCreator(currentUser.getId());
    	dhOverdueTrailer.setCreatorName(currentUser.getName());
    	dhOverdueTrailer.setModified(current);
    	dhOverdueTrailer.setModifier(currentUser.getId());
    	dhOverdueTrailer.setModifierName(currentUser.getName());
    	dhOverdueTrailer.setDpStatus(DpStatus.NORMAL.getCode());
    	dhOverdueTrailer.setTypeData(TypeData.SYSTEM.getCode());
    	dhOverdueTrailer.setId(uuid);
        dhOverdueTrailerService.saveUpdateAndDelete(dhOverdueTrailer, OperateType.add);
        return ApiResponse.success(true);
    }

    /**
     * @author zhangzhengjian <br/>
     * @Title: remove  <br/>
     * @Description: 删除<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	dhOverdueTrailerService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author zhangzhengjian <br/>
     * @Title: disable  <br/>
     * @Description: 禁用<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	dhOverdueTrailerService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author zhangzhengjian <br/>
     * @Title: enable <br/>
     * @Description: 启用<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	dhOverdueTrailerService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author zhangzhengjian <br/>
     * @Title: modify  <br/>
     * @Description: 修改 <br/>
     * @param dhOverdueTrailer
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute DhOverdueTrailer dhOverdueTrailer) {
    	AbstractSysUser currentUser = getCurrentUser();
    	dhOverdueTrailer.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	dhOverdueTrailer.setModifierName(currentUser.getName());
    	dhOverdueTrailerService.saveUpdateAndDelete(dhOverdueTrailer, OperateType.edit);
        return ApiResponse.success(true);
    }
    /**
     * 修改执行组别
     * @param id
     * @param trailerExecutor
     * @return
     */
    @ApiOperation(value = "修改拖车列表执行组别", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public ApiResponse update(String id,String trailerExecutor){
    	AbstractSysUser currentUser = getCurrentUser();
    	DhOverdueTrailer dhOverdueTrailer= new DhOverdueTrailer();
    	if(id!=null && id.contains(",")){
    		String[] ids=id.split(",");
    		for (String sid : ids) {
    			dhOverdueTrailer= new DhOverdueTrailer();
    			dhOverdueTrailer.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    			dhOverdueTrailer.setModifierName(currentUser.getName());
    			dhOverdueTrailer.setId(sid);
    			dhOverdueTrailer.setTrailerExecutor(trailerExecutor);
    			dhOverdueTrailer.setStatusTrailer(10);
    			dhOverdueTrailerService.saveUpdateAndDelete(dhOverdueTrailer, OperateType.edit);
			}
    	}else{
    		dhOverdueTrailer= new DhOverdueTrailer();
			dhOverdueTrailer.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
			dhOverdueTrailer.setModifierName(currentUser.getName());
			dhOverdueTrailer.setId(id);
			dhOverdueTrailer.setTrailerExecutor(trailerExecutor);
			dhOverdueTrailer.setStatusTrailer(10);
			dhOverdueTrailerService.saveUpdateAndDelete(dhOverdueTrailer, OperateType.edit);
    	}
    	return ApiResponse.success(true);
    }

    /**
     * @author zhangzhengjian <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询", response = DhOverdueTrailer.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       DhOverdueTrailer dhOverdueTrailer = dhOverdueTrailerService.selectById(id);
       if(null == dhOverdueTrailer) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(dhOverdueTrailer);
    }
    
    /**
     * @author zhangzhengjian <br/>
     * @Title: list  <br/>
     * @Description: 条件查询 <br/>
     * @param dhOverdueTrailerExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询",response = DhOverdueTrailer.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute DhOverdueTrailerExt dhOverdueTrailerExt){
    	SysUser currentUser = (SysUser)getCurrentUser();
        dhOverdueTrailerExt.notDeleted();
        PageVo page = getPage(dhOverdueTrailerExt);
        dhOverdueTrailerExt.setBankLoan(currentUser.getLoanBank());
        dhOverdueTrailerExt.setCodeUnits( currentUser.getCodeUnits());
        int records = dhOverdueTrailerService.countByExt(dhOverdueTrailerExt);
        page.setRecords(records);
        DhOverdueList dhOverdueList=null;
        if (records > 0) {
            List<DhOverdueTrailer> dpBaseDataDictionaries = dhOverdueTrailerService.selectByExt(dhOverdueTrailerExt);
            for (DhOverdueTrailer dhOverdueTrailer : dpBaseDataDictionaries) {
            	dhOverdueTrailer.setTypeTrailerDisplay(cachedDictionaryService.getName(String.valueOf(dhOverdueTrailer.getTypeTrailer()), DataDicType.TYPE_TRAILER));
            	dhOverdueTrailer.setTrailerExecutorDisplay(cachedDictionaryService.getName(String.valueOf(dhOverdueTrailer.getTrailerExecutor()), DataDicType.TRAILER_EXECUTOR));
            	dhOverdueTrailer.setCommitTime(ZhppDateUtil.stampToDate(dhOverdueTrailer.getCreated(), "yyyy-MM-dd hh:mm:ss"));
            	dhOverdueList= new DhOverdueList();
            	dhOverdueList.setBusiId(dhOverdueTrailer.getBusiId());
            	dhOverdueList=dhOverdueListService.selectRefined(dhOverdueList);
            	if(dhOverdueList!=null){
            		dhOverdueTrailer.setAmountRemainder(dhOverdueList.getAmountRemainder());
            	}
			}
            page.setRows(dpBaseDataDictionaries);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    @ApiOperation(value = "条件查询业务信息",response = DhOverdueTrailerVo.class, httpMethod="POST", tags={"多表查询"})
    @RequestMapping(value = "multiList", method = RequestMethod.POST)
    public ApiResponse multiList(@Validated @ModelAttribute YwBusinessQueryRequest ywBusinessQueryRequest){
        PageVo page = getPage(ywBusinessQueryRequest);
        ywBusinessQueryRequest.notDeleted();
        int records = dhOverdueTrailerService.countMultiByExt(ywBusinessQueryRequest);
        page.setRecords(records);
        if (records > 0) {
            List<DhOverdueTrailerVo> ywBusinesss = dhOverdueTrailerService.selectMultiByExt(ywBusinessQueryRequest);
            for (DhOverdueTrailerVo dhOverdueTrailerVo : ywBusinesss) {
            	dhOverdueTrailerVo.setTypeTrailerDisplay(cachedDictionaryService.getName(String.valueOf(dhOverdueTrailerVo.getTypeTrailer()), DataDicType.TYPE_TRAILER));
			}
            page.setRows(ywBusinesss);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    @ApiOperation(value = "拖车列表导出",response = DhOverdueTrailerVo.class, httpMethod="GET", tags={"多表查询"})
    @RequestMapping(value = "exportExcel", method = RequestMethod.GET)
    public ApiResponse exportExcel(HttpServletResponse response, String customerName,
    		Date submitTimeStart,Date submitTimeEnd,String orgCode){
    	YwBusinessQueryRequest ywBusinessQueryRequest = new YwBusinessQueryRequest();
        ywBusinessQueryRequest.notDeleted();
        ywBusinessQueryRequest.withOutPage();
        ywBusinessQueryRequest.setStatusTrailer(10);
        ywBusinessQueryRequest.setSubmitTimeStart(submitTimeStart);
        ywBusinessQueryRequest.setSubmitTimeEnd(submitTimeEnd);
        ywBusinessQueryRequest.setCustomerName(customerName);
        ywBusinessQueryRequest.setUnitCode(orgCode);
        List<DhOverdueTrailerVo> ywBusinesss = dhOverdueTrailerService.selectExportMultiByExt(ywBusinessQueryRequest);
        DhOverdueList dhOverdueList=null;
        DhOverdueLetterLawyers dhOverdueLetterLawyers=null;
        for (DhOverdueTrailerVo dhOverdueTrailerVo : ywBusinesss) {
        	dhOverdueTrailerVo.setTypeTrailerDisplay(cachedDictionaryService.getName(String.valueOf(dhOverdueTrailerVo.getTypeTrailer()), DataDicType.TYPE_TRAILER));
        	dhOverdueList=new DhOverdueList();
        	dhOverdueList.setBusiId(dhOverdueTrailerVo.getBusiId());
        	dhOverdueList.setOrderSql(" CREATED DESC");
        	DhOverdueList overdue=dhOverdueListService.selectRefined(dhOverdueList);
        	if(overdue!=null){
        		dhOverdueTrailerVo.setAmountRemainder(overdue.getAmountRemainder());
        		dhOverdueTrailerVo.setAmountAmortized(overdue.getAmountAmortized());
        		dhOverdueTrailerVo.setDevideAmount(overdue.getDevideAmount());
        		dhOverdueTrailerVo.setBalanceCard(overdue.getBalanceCard());
        		dhOverdueTrailerVo.setYestAmountMonthly(overdue.getAmountMonthly());
        		dhOverdueTrailerVo.setOverdueCountContinuous(overdue.getOverdueCountContinuous());
        		dhOverdueTrailerVo.setOverdueCountTotal(overdue.getOverdueCountTotal());
        		overdue=null;
        	}
        	dhOverdueLetterLawyers= new DhOverdueLetterLawyers();
        	dhOverdueLetterLawyers.setBusiId(dhOverdueTrailerVo.getBusiId());
        	dhOverdueLetterLawyers.setOrderSql(" CREATED DESC");
        	DhOverdueLetterLawyers dhOverdueLetterLawyer=dhOverdueLetterLawyersService.selectRefined(dhOverdueLetterLawyers);
        	if(dhOverdueLetterLawyer!=null){
        		dhOverdueTrailerVo.setTimeExpress(dhOverdueLetterLawyer.getTimeExpress());
        		dhOverdueLetterLawyer=null;
        	}
		}
        if(ywBusinesss!=null && ywBusinesss.size()>0){
        	String path="";
        	try {
    			HttpSession session = request.getSession();      
    			ServletContext  application  = session.getServletContext();    
    			String serverRealPath = application.getRealPath("/")+"WEB-INF\\" ;
    			path = serverRealPath+new String(fileProperty.getTrailerName().getBytes("ISO-8859-1"),"UTF-8");
    		} catch (UnsupportedEncodingException e) {
    			e.printStackTrace();
    		}
        	importExcel(path,ywBusinesss);
        	downloadExcel(path,response);
        }
        
        
    	return ApiResponse.success(true);
    }
    private void downloadExcel(String pathTo,HttpServletResponse response) {
		try {    
			// path是指欲下载的文件的路径。    
			File file = new File(pathTo);    
			// 取得文件名。    
			String filename = file.getName();   
			// 以流的形式下载文件。    
			InputStream fis = new BufferedInputStream(new FileInputStream(pathTo));    
			byte[] buffer = new byte[fis.available()];    
			fis.read(buffer);    
			fis.close();    
			// 清空response    
			response.reset();    
			// 设置response的Header    
			response.addHeader("Content-Disposition", "attachment;filename="    
					+ new String(filename.getBytes("UTF-8"), "ISO-8859-1"));    
			response.addHeader("Content-Length", "" + file.length());    
			OutputStream toClient = new BufferedOutputStream(    
					response.getOutputStream());    
			response.setContentType("application/vnd.ms-excel;charset=gb2312");    
			toClient.write(buffer);    
			toClient.flush();    
			toClient.close();    
		} catch (IOException ex) {    
			ex.printStackTrace();    
		}    
		
	}

	private void importExcel(String path,List<DhOverdueTrailerVo> ywBusinesss) {
		XSSFWorkbook excel = new XSSFWorkbook();
		XSSFSheet sheet = excel.createSheet("拖车列表名单");
		XSSFRow firstRow = sheet.createRow(0);
		XSSFCell cells[] = new XSSFCell[5];
		  String[] titles = new String[] { "姓名", "车牌号", "部门（区域）", "信贷专员",
		    "证件号","分期金额","月还","入账金额","剩余金额","卡余额","昨日最优还款额","当前连续违约次数","累计违约次数","律师函日期"};
		  for (int i = 0; i < titles.length; i++) {
		   cells[0] = firstRow.createCell(i);
		   cells[0].setCellValue(titles[i]);
		  }
		  DhOverdueTrailerVo dhOverdueTrailer =null;
		  for (int i = 0; i < ywBusinesss.size(); i++) {
		   XSSFRow row = sheet.createRow(i + 1);
		   dhOverdueTrailer = ywBusinesss.get(i);
		   XSSFCell cell = row.createCell(0);
		   cell.setCellValue(dhOverdueTrailer.getCusName());
		   cell = row.createCell(1);
		   cell.setCellValue(dhOverdueTrailer.getLicensePlate());
		   cell = row.createCell(2);
		   cell.setCellValue(dhOverdueTrailer.getUnitName());
		   cell = row.createCell(3);
		   cell.setCellValue(dhOverdueTrailer.getName());
		   cell = row.createCell(4);
		   cell.setCellValue(dhOverdueTrailer.getCusNo());
		   
		   cell = row.createCell(5);
		   cell.setCellValue(dhOverdueTrailer.getDevideAmount()==null?0:dhOverdueTrailer.getDevideAmount());
		   cell = row.createCell(6);
		   cell.setCellValue(dhOverdueTrailer.getAmountMonthly()==null?0:dhOverdueTrailer.getAmountMonthly());
		   cell = row.createCell(7);
		   cell.setCellValue(dhOverdueTrailer.getAmountAmortized()==null?0:dhOverdueTrailer.getAmountAmortized());
		   cell = row.createCell(8);
		   cell.setCellValue(dhOverdueTrailer.getAmountRemainder()==null?0:dhOverdueTrailer.getAmountRemainder());
		   cell = row.createCell(9);
		   cell.setCellValue(dhOverdueTrailer.getBalanceCard()==null?0:dhOverdueTrailer.getBalanceCard());
		   cell = row.createCell(10);
		   cell.setCellValue(dhOverdueTrailer.getYestAmountMonthly()==null?0:dhOverdueTrailer.getYestAmountMonthly());
		   cell = row.createCell(11);
		   cell.setCellValue(dhOverdueTrailer.getOverdueCountContinuous()==null?0:dhOverdueTrailer.getOverdueCountContinuous());
		   cell = row.createCell(12);
		   cell.setCellValue(dhOverdueTrailer.getOverdueCountTotal()==null?0:dhOverdueTrailer.getOverdueCountTotal());
		   cell = row.createCell(13);
		   cell.setCellValue(dhOverdueTrailer.getTimeExpress());
		  }
	        OutputStream out = null;
	        try {
	            out = new FileOutputStream(path);
	            excel.write(out);
	            out.close();
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	 }
		
}
